package com.encryption.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.encryption.dao.Condition;
import com.encryption.dao.UserDAO;
import com.encryption.model.User;
import com.encryption.service.UserService;

/**
 * 用户管理接口实现类
 * 
 * @author Administrator
 * 
 */
public class UserServiceImpl implements UserService {

	private static final Logger log = LoggerFactory
			.getLogger(UserServiceImpl.class);

	private static UserServiceImpl userServiceImpl = null;

	public static UserServiceImpl getUserServiceImpl() {
		if (null == userServiceImpl) {
			userServiceImpl = new UserServiceImpl();
		}
		return userServiceImpl;
	}

	/**
	 * 添加用户
	 * 
	 * @param user
	 */
	public int addUser(User user) {
		try {
			UserDAO.getUserDAO().save(user);
		} catch (Exception e) {
			log.error("添加用户异常", e);
			return -1;
		}
		return user.getId();
	}

	/**
	 * 编辑用户
	 * 
	 * @param user
	 * @return
	 */
	public boolean updateUser(User user) {
		try {
			UserDAO.getUserDAO().merge(user);
		} catch (Exception e) {
			log.error("编辑用户异常", e);
			return false;
		}
		return true;
	}

	/**
	 * 删除用户
	 * 
	 * @param id
	 */
	public boolean deleteUser(String id) {
		try {
			UserDAO.getUserDAO().deleteById(id);
		} catch (Exception e) {
			log.error("删除用户异常", e);
			return false;
		}
		return true;
	}

	/**
	 * 查询用户列表
	 * 
	 * @return
	 */
	public List<User> getUserByCondition(List<Condition> conditions) {
		return UserDAO.getUserDAO().findByExample(conditions);
	}

	/**
	 * 分页查询用户列表
	 * 
	 * @param instance
	 * @param page
	 * @return
	 */
	public List<User> getUserPagingByCondition(List<Condition> condList,
			int page, int pageSize) {
		return UserDAO.getUserDAO()
				.findByExample4Page(condList, page, pageSize);
	}
	
	/**
	 * 分页查询用户列表
	 * 
	 * @param instance
	 * @param page
	 * @return
	 */
	public int getUserCountByCondition(List<Condition> condList) {
		return UserDAO.getUserDAO().findByExample4Count(condList);
	}

	/**
	 * 获取单个用户,根据userid
	 * 
	 * @param userId
	 * @return
	 */
	public User getUserById(int id) {
		return UserDAO.getUserDAO().findById(id);
	}

	/**
	 * 根据登录名获取用户
	 * 
	 * @param loginName
	 */
	public User getUserByLoginName(String loginName) {
		List<User> userList = UserDAO.getUserDAO().findByLoginName(loginName);
		if (userList != null && userList.size() > 0)
			return userList.get(0);
		return null;
	}
}
